package com.sliansoft.wechat.attendance.kit;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.sliansoft.wechat.attendance.entity.ConfigInfo;
import com.sliansoft.wechat.attendance.weixinkit.AesException;
import com.sliansoft.wechat.attendance.weixinkit.SHAEncoder;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * <p>
 * Description:
 * </p>
 * 
 * @author zheng
 * @time 2015年12月10日 下午3:06:19
 */

public class FecthFromWeChat {

	/**
	 * 根据corpId和组管凭证秘钥获取access_token
	 * 
	 * @param corpId
	 * @param corpSecret
	 * @return
	 */
	public static String getAccessToken(String corpId, String corpSecret) {
		String access_token = null;
		CloseableHttpResponse resp = null;
		CloseableHttpClient client = null;

		client = HttpClientBuilder.create().build();
		String url = ContextValue.GETACCESSTOKEN.replace("corpId", corpId).replace("corpSecret", corpSecret);
		HttpPost post = new HttpPost(url);

		try {
			resp = client.execute(post);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("执行post请求时出错");
		}

		int statusCode = resp.getStatusLine().getStatusCode();

		if (statusCode >= 200 && statusCode < 300) {
			HttpEntity entity = resp.getEntity();

			String content = null;
			try {
				content = EntityUtils.toString(entity);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				// 这里最好再进行一下判断
				JSONObject obj = JSONObject.fromObject(content);
				access_token = obj.getString("access_token");
			} catch (JSONException jsonException) {
				jsonException.printStackTrace();
				System.out.println("获取access_token时出错");
			}
		}

		System.out.println(access_token);
		return access_token;
	}

	/**
	 * 根据code参数获取成员信息
	 * 
	 * @param access_token
	 * @param code
	 * @return
	 */
	public static String getUserId(String access_token, String code) {
		System.out.println("getUserId");
		CloseableHttpResponse resp = null;
		CloseableHttpClient client = null;

		// JSONObject jsonObject = new JSONObject();
		// jsonObject.put("access_token", access_token);
		// jsonObject.put("code", code);

		client = HttpClientBuilder.create().build();
		String url = ContextValue.GETUSERINFO.replace("ACCESS_TOKEN", access_token);
		url = url.replace("CODE", code);
		HttpPost post = new HttpPost(url);
		// post.addHeader("Content-Type", "application/json");
		// StringEntity stringEntity = new StringEntity(jsonObject.toString(),
		// ContentType.create("application/json", "utf-8"));
		// post.setEntity(stringEntity);

		try {
			resp = client.execute(post);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("执行post请求时出错");
		}

		int statusCode = resp.getStatusLine().getStatusCode();
		String userId = null;

		if (statusCode >= 200 && statusCode < 300) {
			HttpEntity entity = resp.getEntity();

			String content = null;
			try {
				content = EntityUtils.toString(entity);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				// 这里最好再进行一下判断
				JSONObject obj = JSONObject.fromObject(content);
				userId = obj.getString("UserId");
			} catch (JSONException jsonException) {
				jsonException.printStackTrace();
				System.out.println("获取userId时出错");
			}
		}
		return userId;
	}

	public static String getSignature(String access_token) throws AesException {
		String signature = null;
		String jsapi_ticket = null;
		CloseableHttpResponse resp = null;
		CloseableHttpClient client = null;

		client = HttpClientBuilder.create().build();
		String url = ContextValue.GETSIGNATURE.replace("ACCESS_TOKEN", access_token);
		HttpPost post = new HttpPost(url);

		try {
			resp = client.execute(post);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("执行post请求时出错");
		}

		int statusCode = resp.getStatusLine().getStatusCode();

		if (statusCode >= 200 && statusCode < 300) {
			HttpEntity entity = resp.getEntity();

			String content = null;
			try {
				content = EntityUtils.toString(entity);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				// 这里最好再进行一下判断
				JSONObject obj = JSONObject.fromObject(content);
				jsapi_ticket = obj.getString("ticket");
			} catch (JSONException jsonException) {
				jsonException.printStackTrace();
				System.out.println("获取ticket时出错");
			}
		}

		System.out.println("jsapi_ticket=" + jsapi_ticket);

		// 根据jsapi_ticket生成signature
		StringBuilder stringBuilder = new StringBuilder("jsapi_ticket=");
		long timestamp = System.currentTimeMillis() / 1000;
		String rowsignature = stringBuilder.append(jsapi_ticket).append("&noncestr=zdwssq").append("&timestamp=")
				.append(timestamp)
				.append("&url=http://zdwssq.picp.net/app-mobile-attendance-web/html/todayAttendance.html").toString();
		System.out.println("timestamp = " + timestamp);

		signature = SHAEncoder.sha(rowsignature);

		return signature;
	}

	public static ConfigInfo getConfigInfo(String accesstoken, String currentUrl, HttpServletRequest request,
			HttpServletResponse response) throws AesException {
		String jsapi_ticket = null;
		String signature = null;
		ConfigInfo configInfo = null;
		/**
		 * 下面的内容需要强烈注意：不要每次都请求新的配置信息，要先判断jsapi-ticket是否存在，
		 * 不存在的话再去获取最新的，然后把最新的放在cookie中
		 */
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ((cookie.getName()).equals("jsapi_ticket")) {
					jsapi_ticket = cookie.getValue();
					break;
				} else
					continue;
			}
		}
		if (jsapi_ticket == null) {
			CloseableHttpResponse resp = null;
			CloseableHttpClient client = null;

			client = HttpClientBuilder.create().build();
			String url = ContextValue.GETSIGNATURE.replace("ACCESS_TOKEN", accesstoken);
			HttpPost post = new HttpPost(url);

			try {
				resp = client.execute(post);
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("执行post请求时出错");
			}

			int statusCode = resp.getStatusLine().getStatusCode();

			if (statusCode >= 200 && statusCode < 300) {
				HttpEntity entity = resp.getEntity();

				String content = null;
				try {
					content = EntityUtils.toString(entity);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					JSONObject obj = JSONObject.fromObject(content);
					jsapi_ticket = obj.getString("ticket");
					Cookie cookie = new Cookie("jsapi_ticket", jsapi_ticket);
					cookie.setMaxAge(70000);// 单位为秒
					response.addCookie(cookie);
				} catch (JSONException jsonException) {
					jsonException.printStackTrace();
					System.out.println("获取ticket时出错");
				}
			}
		}

		if (jsapi_ticket != null) {
			// 根据jsapi_ticket生成signature
			StringBuilder stringBuilder = new StringBuilder("jsapi_ticket=");
			long timestamp = System.currentTimeMillis() / 1000;
			String rowsignature = stringBuilder.append(jsapi_ticket).append("&noncestr=zdwssq").append("&timestamp=")
					.append(timestamp).append("&url=").append(currentUrl).toString();
			signature = SHAEncoder.sha(rowsignature);

			configInfo = new ConfigInfo();
			configInfo.setTimestamp(String.valueOf(timestamp));
			configInfo.setSignature(signature);
			configInfo.setNonceStr("zdwssq");
		}

		return configInfo;
	}
}
